package tungsten.base.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

/**
 * Created by Lv on 2016/6/12.
 */
public abstract class BaseServer
{
    private int port;

    private static Logger logger = Logger.getLogger(BaseServer.class);
    private EventLoopGroup work;
    private EventLoopGroup boss;

    public int getPort()
    {
        return this.port;
    }

    public void listener(int port)
    {
        this.port = port;
        logger.info("begin to listen:" + this.port);
        boss = new NioEventLoopGroup();
        work = new NioEventLoopGroup();
        try
        {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss,work);

            bootstrap.channel(NioServerSocketChannel.class);

            bootstrap.childHandler(getChildHandler());

            bootstrap.option(ChannelOption.SO_BACKLOG,1024);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
            bootstrap.bind(this.port).sync().channel().closeFuture().sync();
        }
        catch (Exception e)
        {
            logger.error("",e);
        }
        finally
        {
            work.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    public void dispose()
    {
        try
        {
            if(work != null) work.shutdownGracefully();
            if(boss != null) boss.shutdownGracefully();
        }
        catch (Exception e)
        {
            logger.error("",e);
        }
    }
    /**
     * 返回相关的解码器
     * @return
     */
    protected abstract ChannelInboundHandlerAdapter getChildHandler();
}